package openbang.account.service.impl;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openbang.account.service.entity.UserAccount;
import openbang.account.service.entity.VerifyRecord;
import openbang.account.service.util.PMF;
import openbang.account.service.util.SessionHelper;
import openbang.account.service.vo.BusinessEnum;
import openbang.account.service.vo.VerifyStatusEnum;

/**
 * 普通的Servlet
 * 用户注册后，在收到的邮件里,单击URL的响应处理 -- 判断用户是否通过邮箱验证
 * @author aibozeng
 *
 */

@SuppressWarnings("serial")
public class VerifyEmailServlet extends HttpServlet{
	private static final Logger log = Logger.getLogger(VerifyEmailServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
		String email = req.getParameter("email");
		String uuid = req.getParameter("id");
		log.info("come in VerifyEmailServlet email="+email+",id="+uuid);
		if(email==null ||uuid==null){			
			SessionHelper.forwardToErrorPage(BusinessEnum.VERIFY_EMAIL.getDesc(),"参数为空","从邮件里重新拷贝URL到浏览器地址栏", req, resp);
			return;
		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(VerifyRecord.class);
		q.setFilter("status=="+VerifyStatusEnum.PENDING.getCode()+"&& busiType == "+BusinessEnum.VERIFY_EMAIL.getCode()+" && email == email_address && verifyCode== verify_code ");
		q.setOrdering("applyTime desc");
		q.setRange(0,1); //找出最新
		q.declareParameters("java.lang.String email_address , java.lang.String verify_code");
		Collection<VerifyRecord> users = (Collection<VerifyRecord>) q.execute(email, uuid);
		VerifyRecord findPwdRecord = null;
		if(users!=null && users.size()>0){
			findPwdRecord = users.iterator().next();
		}
		else{
			pm.close();
			SessionHelper.forwardToErrorPage(BusinessEnum.VERIFY_EMAIL.getDesc(),"申请记录找不到","请重新申请邮箱验证", req, resp);
			return;			
		}
		
		//验证邮箱成功
		UserAccount userAccount = (new AccountServiceImpl()).findByEmail(findPwdRecord.getEmail(),pm);
		userAccount.setUpdTime(new Date());
		userAccount.setEmailVerifyStatus(VerifyStatusEnum.CONFIRM.getCode());
		findPwdRecord.setStatus(VerifyStatusEnum.CONFIRM.getCode());
		findPwdRecord.setConfirmTime(new Date());
		findPwdRecord.setUpdTime(findPwdRecord.getConfirmTime());
		pm.close();

		SessionHelper.forwardToSuccessPage(BusinessEnum.VERIFY_EMAIL.getDesc(),"请单击<a href=\""+SessionHelper.getAppUrl(req)+"\">首页</a>返回", req, resp);
		return;
    }
	

}
